package com.fairylove.rpc.handler;

import com.fairylove.rpc.entity.RpcRequest;
import com.fairylove.rpc.provider.ServiceProvider;
import com.fairylove.rpc.provider.ServiceProviderImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;


/**
 * 进行远程调用的处理器
 */
public class RequestHandler {
     private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
     private static ServiceProvider serviceProvider;

     static {
         serviceProvider = new ServiceProviderImpl();
     }
     public Object handler(RpcRequest request){
         //后续是提供一个服务列表 找到要查询到的服务
         Object service = RequestHandler.serviceProvider.getServiceProvider(request.getInterfaceName());
         return invorkTargetMethod(request,service);
     }

     public Object invorkTargetMethod(RpcRequest request,Object service){
         Object result = null;
         try{
             //根据方法名和方法参数获得method
             Method method = service.getClass().getMethod(request.getMethodName(), request.getParamTypes());
             result = method.invoke(service, request.getParameters());
             logger.info("调用了服务：{},方法为：{}", request.getInterfaceName(),request.getMethodName());
         } catch (Exception  e) {
             logger.error("服务调用失败" + e);
         }
         return result;
     }
}
